package cs341.group2.mycontacts;

import java.util.ArrayList;

import cs341.group2.mycontacts.Database.Category;
import cs341.group2.mycontacts.Database.Contact;
import cs341.group2.mycontacts.Database.MyContactsDB;

import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.InputType;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class ContactPage extends Activity {

	private String state;
	private MyContactsDB myContactsDb;
	protected Object mEdit;
	private AlertDialog bri;
	private ArrayAdapter<Category> spinnerAdapter = null;
	ArrayList<Category> categoryList = null;
	private int ContactId = -1;
	private Category[] Categories = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact);
		myContactsDb = new MyContactsDB(this);
		Bundle extras = getIntent().getExtras();
		
		//view,add,edit are the three keywords for states
		state = extras.getString("state");//if we are viewing an existing contact, get the passed in conatactId, otherwise, keep Id as -1
		
		ContactId = extras.getInt("contactId");
		
		
		/*myContactsDb.open();
		Category[] category = myContactsDb.getAllCategories();
		myContactsDb.close();*/

		// Write method to set states of fields here in order to display the
		// page properly.

		Button b = (Button) findViewById(R.id.button_groups);
		b.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(ContactPage.this,
						cs341.group2.mycontacts.MainActivity.class);
				startActivity(i);
			}
		});

		Button b2 = (Button) findViewById(R.id.button_search);
		b2.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				Intent i = new Intent(ContactPage.this,
						cs341.group2.mycontacts.Search.class);
				startActivity(i);
			}
		});

		final Button b3 = (Button) findViewById(R.id.button_left);
		b3.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				if(state.equalsIgnoreCase("view")){
					state = "edit";
					b3.setText("Save");
					Button bRight = (Button) findViewById(R.id.button_right);
					bRight.setVisibility(View.VISIBLE);
					bRight.setText("Delete");
					actionState("edit");
				}
				else if(state.equalsIgnoreCase("edit")){
					state= "view";
					Contact contact = MakeContact(ContactId);
					new UpdateContact().execute(contact);
					Button bRight = (Button) findViewById(R.id.button_right);
					bRight.setVisibility(View.GONE);
					b3.setText("Edit Contact");
					actionState(state);
				}
				else{
					Contact contact = MakeContact(-1);
					new AddContact().execute(contact);
				}
				
			}
		});
		
		final Button b4 = (Button) findViewById(R.id.button_right);
		b4.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				AlertDialog.Builder build  = new AlertDialog.Builder(ContactPage.this);
				build.setTitle("Warning");
				build.setMessage("Do you want to delete this Contact");
				build.setPositiveButton("yes", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						new DeleteContact().execute(ContactId);
					}
				});
				build.setNegativeButton("No", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						bri.cancel();
					}
				});
				bri =build.create();
				bri.show();
				
			}
		});

	}

	public void lockAllBoxes() {
		EditText box = (EditText) findViewById(R.id.first_name);
		box.setEnabled(false);
		box.setInputType(InputType.TYPE_NULL);

		box = (EditText) findViewById(R.id.cell);
		box.setEnabled(false);
		box.setInputType(InputType.TYPE_NULL);

		box = (EditText) findViewById(R.id.alt);
		box.setEnabled(false);
		box.setInputType(InputType.TYPE_NULL);

		box = (EditText) findViewById(R.id.address);
		box.setEnabled(false);
		box.setInputType(InputType.TYPE_NULL);

		box = (EditText) findViewById(R.id.city_state);
		box.setEnabled(false);
		box.setInputType(InputType.TYPE_NULL);

		box = (EditText) findViewById(R.id.comment);
		box.setEnabled(false);
		box.setInputType(InputType.TYPE_NULL);

		box = (EditText) findViewById(R.id.email);
		box.setEnabled(false);
		box.setInputType(InputType.TYPE_NULL);
		
		Spinner spin = (Spinner) findViewById(R.id.spinner_groups);
		spin.setEnabled(false);
		spin.setClickable(false);
	}

	public void unlockAllBoxes() {
		EditText box = (EditText) findViewById(R.id.first_name);
		box.setEnabled(true);
		box.setInputType(InputType.TYPE_CLASS_TEXT);

		box = (EditText) findViewById(R.id.cell);
		box.setEnabled(true);
		box.setInputType(InputType.TYPE_CLASS_PHONE);

		box = (EditText) findViewById(R.id.alt);
		box.setEnabled(true);
		box.setInputType(InputType.TYPE_CLASS_PHONE);

		box = (EditText) findViewById(R.id.address);
		box.setEnabled(true);
		box.setInputType(InputType.TYPE_CLASS_TEXT);

		box = (EditText) findViewById(R.id.city_state);
		box.setEnabled(true);
		box.setInputType(InputType.TYPE_CLASS_TEXT);

		box = (EditText) findViewById(R.id.comment);
		box.setEnabled(true);
		box.setInputType(InputType.TYPE_CLASS_TEXT);

		box = (EditText) findViewById(R.id.email);
		box.setEnabled(true);
		box.setInputType(InputType.TYPE_CLASS_TEXT);
		
		Spinner spin = (Spinner) findViewById(R.id.spinner_groups);
		spin.setEnabled(true);
		spin.setClickable(true);
	}

	public void populateFields(Contact contact) {
		EditText box = (EditText) findViewById(R.id.first_name);
		box.setText(contact.Name == null ? "Name" : contact.Name);

		box = (EditText) findViewById(R.id.cell);
		box.setText(contact.CellPhone == null ? "Cell Phone" : contact.CellPhone);

		box = (EditText) findViewById(R.id.alt);
		box.setText(contact.AltPhone == null ? "Alt Phone" : contact.AltPhone);

		box = (EditText) findViewById(R.id.address);
		box.setText(contact.Address == null ? "Address" : contact.Address);

		box = (EditText) findViewById(R.id.city_state);
		box.setText(contact.CityZip == null ? "City Ziptest" : contact.CityZip);

		box = (EditText) findViewById(R.id.email);
		box.setText(contact.Email == null ? "Email" : contact.Email);

		box = (EditText) findViewById(R.id.comment);
		box.setText(contact.Comments == null ? "Comments" : contact.Comments);
		
		int pos = -1;
		for (Category cat : categoryList){
			if(cat.Id == contact.CategoryId){
				pos = categoryList.indexOf(cat);
			}
		}
		Spinner mySpinner = (Spinner)findViewById(R.id.spinner_groups);
		mySpinner.setSelection(pos);

	}
	
	public void actionState(String state)
	{
		if (state.equalsIgnoreCase("add")) {
			Contact contact = new Contact();

			EditText text = (EditText) findViewById(R.id.first_name);
			String first = text.getText().toString();

			text = (EditText) findViewById(R.id.cell);
			contact.CellPhone = text.getText().toString();

			text = (EditText) findViewById(R.id.alt);
			contact.AltPhone = text.getText().toString();

			text = (EditText) findViewById(R.id.email);
			contact.Email = text.getText().toString();

			text = (EditText) findViewById(R.id.address);
			contact.Address = text.getText().toString();

			text = (EditText) findViewById(R.id.city_state);
			contact.CityZip = text.getText().toString();

			 text = (EditText) findViewById(R.id.comment);
			 contact.Comments = text.getText().toString();

			myContactsDb.open();

			myContactsDb.insertContact(contact);

			myContactsDb.close();
		}
		
		else if(state.equalsIgnoreCase("edit"))
		{
			unlockAllBoxes();
		}
		
		else if(state.equalsIgnoreCase("view")){
			lockAllBoxes();
		}
	}
	
	public void viewState(Contact contact)
	{
		if(state.equalsIgnoreCase("add"))
		{
			Button left = (Button) findViewById(R.id.button_left);
			left.setText("Add Contact");
			Button right = (Button) findViewById(R.id.button_right);
			right.setVisibility(View.GONE);
			unlockAllBoxes();
		}
		
		else if(state.equalsIgnoreCase("view"))
		{
			Button left = (Button) findViewById(R.id.button_left);
			Button right = (Button) findViewById(R.id.button_right);
			right.setVisibility(View.GONE);
			left.setText("Edit Contact");
			left.setId(contact.Id);
			populateFields(contact);
			lockAllBoxes();
		}
		
			
			
		
	}
	
	public Contact MakeContact(int contactId){
		Contact contact = new Contact();
		contact.Id = contactId;
		EditText box = (EditText) findViewById(R.id.first_name);
		contact.Name = box.getText().toString();
		box = (EditText) findViewById(R.id.cell);
		contact.CellPhone = box.getText().toString().equalsIgnoreCase("Cell Phone") ? "" : box.getText().toString();
		box = (EditText) findViewById(R.id.alt);
		contact.AltPhone = box.getText().toString().equalsIgnoreCase("Alt Phone") ? "" : box.getText().toString();
		box = (EditText) findViewById(R.id.email);
		contact.Email = box.getText().toString().equalsIgnoreCase("Email") ? "" : box.getText().toString();
		box = (EditText) findViewById(R.id.address);
		contact.Address = box.getText().toString().equalsIgnoreCase("Address") ? "" : box.getText().toString();
		box = (EditText) findViewById(R.id.city_state);
		contact.CityZip = box.getText().toString().equalsIgnoreCase("City Zip") ? "" : box.getText().toString();
		box = (EditText) findViewById(R.id.comment);
		contact.Comments = box.getText().toString().equalsIgnoreCase("Comments") ? "" : box.getText().toString();
		
		Spinner mySpinner = (Spinner)findViewById(R.id.spinner_groups);
		Category cat = (Category)spinnerAdapter.getItem(mySpinner.getSelectedItemPosition());
		if(cat.Id != -1){
			contact.CategoryId = cat.Id;
		}
		
		
		return contact;
	}
	
	public void populateCategoryItems(Category[] categories){
		Spinner spinner = (Spinner)findViewById(R.id.spinner_groups);
		Category[] cats = new Category[categories.length + 1];
		ArrayList<Category> caters = new ArrayList<Category>();
		Category temp = new Category();
		temp.Id = -1;
		temp.Name = "Select A Category";
		cats[0] = temp;
		caters.add(temp);
		for(int i = 0; i < categories.length; i ++){
			temp = new Category();
			temp.Id = categories[i].Id;
			temp.Name = categories[i].Name;
			cats[i + 1] = temp;
			caters.add(temp);
		}
		categoryList = caters;
		spinnerAdapter = new ArrayAdapter<Category>(this, android.R.layout.simple_spinner_item, caters);
		spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(spinnerAdapter);
		
		//after category setup, check state and adjust accordingly
		if(state.equalsIgnoreCase("view")){
			new GetContactInformation().execute(ContactId);
		}
		else{
			viewState(new Contact());
		}
	}
	
	@Override
	public void onResume() {
		super.onResume(); // Always call the superclass method first
		new PopulateAllCategories().execute();
	}
	
	private class GetContactInformation extends AsyncTask<Integer, Object, Contact> {
		public MyContactsDB myContactsDb = new MyContactsDB(ContactPage.this);

		protected Contact doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			myContactsDb.open();
			return myContactsDb.GetContactInformation(params[0]);
		}
		
		protected void onPostExecute(Contact contact) {
			myContactsDb.close();
			viewState(contact);
		}
	}
	
	private class UpdateContact extends AsyncTask<Contact, Object, Object> {
		public MyContactsDB myContactsDb = new MyContactsDB(ContactPage.this);

		protected Object doInBackground(Contact... params) {
			// TODO Auto-generated method stub
			myContactsDb.open();
			myContactsDb.UpdateContactInformation(params[0]);
			return (Object[]) null;
		}
		
		protected void onPostExecute(Object o) {
			myContactsDb.close();
		}
	}
	
	private class AddContact extends AsyncTask<Contact, Object, Integer> {
		public MyContactsDB myContactsDb = new MyContactsDB(ContactPage.this);

		protected Integer doInBackground(Contact... params) {
			// TODO Auto-generated method stub
			myContactsDb.open();
			return myContactsDb.insertContact(params[0]);
		}
		
		protected void onPostExecute(Integer contactId) {
			myContactsDb.close();
			Intent i = new Intent(ContactPage.this,
					cs341.group2.mycontacts.ContactPage.class);
			i.putExtra("state", "view");
			i.putExtra("contactId", contactId);
			startActivity(i);
		}
	}
	
	private class PopulateAllCategories extends
		AsyncTask<Object, Object, Category[]> {
	public MyContactsDB myContactsDb = new MyContactsDB(ContactPage.this);
	
	@Override
	protected Category[] doInBackground(Object... params) {
		myContactsDb.open();
		return myContactsDb.getAllCategories();
		
	}
	
	@Override
	protected void onPostExecute(Category[] categories) {
		myContactsDb.close();
		Categories = categories;
		populateCategoryItems(categories);
	}
	}
		
		private class DeleteContact extends
		AsyncTask<Integer, Object, Object> {
	public MyContactsDB myContactsDb = new MyContactsDB(ContactPage.this);
	
	@Override
	protected Object doInBackground(Integer... params) {
		myContactsDb.open();
		myContactsDb.DeleteContact(params[0]);
		return (Object[]) null;
	}
	
	@Override
	protected void onPostExecute(Object o) {
		myContactsDb.close();
		Intent i = new Intent(ContactPage.this,
				cs341.group2.mycontacts.MainActivity.class);
		startActivity(i);
	}
	}
		
		

}
